package main.java.com.lx.tools.generator

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTabbedPane
import main.java.com.lx.tools.utils.NotificationUtil
import main.java.com.lx.tools.utils.PlatformUtil
import main.java.com.lx.tools.utils.UIUtil
import java.awt.GridBagLayout
import java.net.InetAddress
import javax.swing.Action
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JPanel


class ActionGenerator : AnAction() {
    /**
     * 执行相关的动作
     */
    override fun actionPerformed(event: AnActionEvent?) {
        if (event == null) {
            return
        }
        val project = event.project ?: return
        val content = JPanel(GridBagLayout())
        val tabPane = JBTabbedPane()
        //数据库配置tab页
        val tabPanelDB = JPanel(GridBagLayout())
        //数据库配置tab页输入框
        val urlInput = UIUtil.addTextInputToPanel("请输入数据库链接的URL(com.mysql.jdbc.Driver):", MyConstant.DB_URL, tabPanelDB)
        val userNameInput = UIUtil.addTextInputToPanel("请输入用户名:", MyConstant.DB_USER, tabPanelDB)
        val passwordInput = UIUtil.addTextInputToPanel("请输入密码:", MyConstant.DB_PW, tabPanelDB)
        //数据库配置tab页清除按钮
        val clearDBCacheBtn = JButton("清除配置")
        clearDBCacheBtn.border = IdeBorderFactory.createEmptyBorder(10, 10, 10, 10)
        tabPanelDB.add(clearDBCacheBtn, ExternalSystemUiUtil.getLabelConstraints(0))
        clearDBCacheBtn.addActionListener {
            urlInput.text = ""
            userNameInput.text = ""
            passwordInput.text = ""
            PlatformUtil.setData(MyConstant.DB_URL, "")
            PlatformUtil.setData(MyConstant.DB_USER, "")
            PlatformUtil.setData(MyConstant.DB_PW, "")
            PlatformUtil.setData(MyConstant.DB_CONF_INITED, false)
            NotificationUtil.info("清除配置成功", project)
        }
        //数据库配置tab页保存按钮
        val saveDBCacheBtn = JButton("保存配置")
        saveDBCacheBtn.border = IdeBorderFactory.createEmptyBorder(10, 10, 10, 10)
        tabPanelDB.add(saveDBCacheBtn, ExternalSystemUiUtil.getLabelConstraints(0))
        saveDBCacheBtn.addActionListener {
            if (urlInput.text.trim().isBlank()
                    || userNameInput.text.trim().isBlank()
                    || passwordInput.text.trim().isBlank()
                    ) {
                NotificationUtil.popInfo("配置不能为空", event)
            } else {
                PlatformUtil.setData(MyConstant.DB_URL, urlInput.text)
                PlatformUtil.setData(MyConstant.DB_USER, userNameInput.text)
                PlatformUtil.setData(MyConstant.DB_PW, passwordInput.text)
                PlatformUtil.setData(MyConstant.DB_CONF_INITED, true)
                NotificationUtil.popInfo("数据库配置修改成功", event)
            }
        }
        tabPanelDB.border = IdeBorderFactory.createEmptyBorder(0, 0, 8, 0)
        tabPane.addTab("数据库配置", tabPanelDB)
        //路径配置修tab页
        val tabPanelPath = JPanel(GridBagLayout())
        val daoPackagePath = UIUtil.addTextInputToPanel("Domain,Mapper所在package:", MyConstant.DAO_PACKAGE, tabPanelPath)
        val servicePackagePath = UIUtil.addTextInputToPanel("Service所在的package:", MyConstant.SERVICE_PACKAGE, tabPanelPath)
        val tablePrefix = UIUtil.addTextInputToPanel("表名的前缀(生成class的时候去掉前缀):", MyConstant.TABLE_PREFIX, tabPanelPath)
        val clearPathCacheBtn = JButton("清除配置")
        clearPathCacheBtn.border = IdeBorderFactory.createEmptyBorder(10, 10, 10, 10)
        clearPathCacheBtn.addActionListener {
            daoPackagePath.text = ""
            servicePackagePath.text = ""
            tablePrefix.text = ""
            PlatformUtil.setData(MyConstant.DAO_PACKAGE, "")
            PlatformUtil.setData(MyConstant.SERVICE_PACKAGE, "")
            PlatformUtil.setData(MyConstant.TABLE_PREFIX, "")
            MyBatisGenConst.clearConfig()
            NotificationUtil.info("清除配置成功", project)
        }
        tabPanelPath.add(clearPathCacheBtn, ExternalSystemUiUtil.getLabelConstraints(0))
        val savePathCacheBtn = JButton("保存配置")
        savePathCacheBtn.border = IdeBorderFactory.createEmptyBorder(10, 10, 10, 10)
        tabPanelPath.add(savePathCacheBtn, ExternalSystemUiUtil.getLabelConstraints(0))
        savePathCacheBtn.addActionListener {
            if (daoPackagePath.text.trim().isBlank() || servicePackagePath.text.trim().isBlank()) {
                NotificationUtil.popError("路径配置不能为空", event)
            } else {
                PlatformUtil.setData(MyConstant.DAO_PACKAGE, daoPackagePath.text)
                PlatformUtil.setData(MyConstant.SERVICE_PACKAGE, servicePackagePath.text)
                PlatformUtil.setData(MyConstant.TABLE_PREFIX,tablePrefix.text)
                NotificationUtil.popInfo("路径配置修改成功", event)
            }
        }
        tabPanelPath.border = IdeBorderFactory.createEmptyBorder(0, 0, 8, 0)
        tabPane.addTab("路径配置", tabPanelPath)
        //代码生成tab页
        val tabPanelCreate = JPanel(GridBagLayout())
        val tableHistory = UIUtil.addTextInputToPanel("请输入需要产生代码的表名，以,隔开:", MyConstant.TABLE_HISTORY, tabPanelCreate)
        val clearCreateCacheBtn = JButton("清除表名")
        clearCreateCacheBtn.border = IdeBorderFactory.createEmptyBorder(10, 10, 10, 10)
        clearCreateCacheBtn.addActionListener {
            PlatformUtil.setData(MyConstant.TABLE_HISTORY, "")
            NotificationUtil.info("清除表名成功", project)
            tableHistory.text = ""
        }
        tabPanelCreate.add(clearCreateCacheBtn, ExternalSystemUiUtil.getLabelConstraints(0))
        tabPanelCreate.border = IdeBorderFactory.createEmptyBorder(-100, 0, 8, 0)
        tabPane.addTab("代码生成", tabPanelCreate)
        //默认tab
        tabPane.selectedIndex = 0
        content.add(tabPane, ExternalSystemUiUtil.getLabelConstraints(0))
        content.border = IdeBorderFactory.createEmptyBorder(0, 0, 8, 0)

        val ia = InetAddress.getLocalHost()
        object : DialogWrapper(project) {
            init {
                title = "代码生成工具（IP：" + ia.hostAddress + "）"
                myOKAction.putValue("Name", "立即生成代码")
                init()
            }

            override fun createCenterPanel(): JComponent? {
                return JBScrollPane(content)
            }

            override fun createActions(): Array<Action> {
                return arrayOf(okAction)
            }

            override fun doOKAction() {
                if (!PlatformUtil.getData(MyConstant.DB_CONF_INITED, false)) {
                    NotificationUtil.popInfo("请配置数据库连接", event)
                    tabPane.selectedIndex = 0
                } else if (!MyBatisGenConst.initCodeConfig(project)) {
                    NotificationUtil.popInfo("请设置生成代码路径", event)
                    tabPane.selectedIndex = 1
                } else {
                    val tableNames = mutableSetOf<String>()
                    tableHistory.text?.split(",")?.let { tableNames.addAll(it.filter { !it.isBlank() }) }
                    if (tableNames.size == 0) {
                        NotificationUtil.popInfo("请填写需要生成的表名", event)
                    } else {
                        PlatformUtil.executeBackgroundTask(project, "正在生成代码", Runnable {
                            val exception = MybatisCore.batchGen(tableNames.toList(), project)
                            if (exception == null) {
                                NotificationUtil.popInfo("生成代码成功,详情见EventLog控制台输出", event)
                            } else {
                                NotificationUtil.popError("生成代码出错,详情见EventLog控制台输出", event)
                                NotificationUtil.error("生成代码出错exception:" + exception)
                            }
                            PlatformUtil.notifyFileChanged(project)
                        })
                        PlatformUtil.setData(MyConstant.TABLE_HISTORY, tableHistory.text)
                        if (this.okAction.isEnabled) {
                            this.close(0)
                        }
                    }
                }
            }
        }.showAndGet()

    }


}